package cn.jsprun.service.posts;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import cn.jsprun.dao.DataBaseDao;
import cn.jsprun.dao.posts.PmsDao;
import cn.jsprun.domain.Pms;
import cn.jsprun.struts.form.PmsForm;
import cn.jsprun.utils.BeanFactory;
public class PmsService {
	private Pms pmsFormToPms(PmsForm pf) {
		Pms p = new Pms();
		p.setMsgfrom(pf.getMsgfrom());
		p.setMsgfromid(pf.getMsgfromid());
		p.setMsgtoid(pf.getMsgtoid());
		p.setFolder(pf.getFolder());
		p.setNew_(pf.getNew_());
		p.setSubject(pf.getSubject());
		p.setDateline(pf.getDateline());
		p.setMessage(pf.getMessage());
		p.setDelstatus(pf.getDelstatus());
		return p;
	}
	private List<Pms> pmsListToPmsList(List<PmsForm> pmsFormList) {
		List<Pms> pmsList = new ArrayList<Pms>();
		for (int i = 0; i < pmsFormList.size(); i++) {
			pmsList.add(pmsFormToPms(pmsFormList.get(i)));
		}
		return pmsList;
	}
	public void insertPmsList(List<PmsForm> pmsFormList) {
		if (pmsFormList != null && pmsFormList.size() > 0) {
			int timestamp = (int)(Calendar.getInstance().getTimeInMillis()/1000);
			PmsDao pmsDao =(PmsDao) BeanFactory.getBean("pmsDao");
			DataBaseDao dataBaseDao = (DataBaseDao)BeanFactory.getBean("dataBaseDao");
			for (int i = 0; i < pmsFormList.size(); i++) {
				PmsForm pmsForm = pmsFormList.get(i);
				if (pmsForm.isThreads()) {
					String action = "";
					if (pmsForm.isType()) {
						action = "MOD";
					} else {
						action="DEL";
					}
					dataBaseDao.runQuery("update jrun_members set newpm=1 where uid="+pmsForm.getMsgtoid());
					dataBaseDao.runQuery("INSERT INTO jrun_threadsmod (tid, uid, username, dateline, action, expiration, status) VALUES('"+pmsForm.getPostsId()+"','"+pmsForm.getMsgfromid()+"','"+pmsForm.getMsgfrom()+"','"+timestamp+"','"+action+"','0','1')");
				}else{
					dataBaseDao.runQuery("update jrun_members set newpm=1 where uid="+pmsForm.getMsgtoid());
				}
			}
			pmsDao.insertPmsList(pmsListToPmsList(pmsFormList));
			pmsDao=null;dataBaseDao=null;
		}
	}
}
